import { defineStore } from "pinia";
import { ref } from "vue";
import { useUserStore } from './user'
import { BaseUrlType } from "@/types/request";
import baseUrl from '@/config/baseUrl';
import icon_inform from '@/static/image/icon/icon_inform.png'
import dayjs from 'dayjs'

interface MessageItemTypes {
  icon: string;
  title: string;
  desc: string;
  sendTime: string;
}

export const useMsgStore = defineStore("msg", () => {
  const linkWs = ref<Boolean>(false); // 是否已连接websocket
  const messages = ref<MessageItemTypes[]>([]);

  /** 
   * 链接websocket
   */
  function linkWebSocket() {
    const { userInfo, getUserInfo } = useUserStore();
    if (userInfo && userInfo.userId && !linkWs.value) {
      const _nodeEnv = window.location.hostname.indexOf('test') !== -1 ? `ws_${process.env.NODE_ENV}_test` : `ws_${process.env.NODE_ENV}`;
      const wsUrl = baseUrl[_nodeEnv as BaseUrlType] + userInfo.userId; // ws路径
      uni.connectSocket({
        url: wsUrl
      });
      uni.onSocketMessage(function (_r) {
        const res = JSON.parse(_r.data);
        console.log(res);

        if (res.code === 1000) { // 系统通知
          messages.value.push({
            icon: icon_inform,
            title: '系统通知',
            desc: '关注公众号成功', // MP_FOLLOW_REMIND
            sendTime: dayjs().format('YYYY-MM-DD HH:mm')
          })
          getUserInfo()
        }else if(res.code === 1001 || res.code === 1002) {
          linkWs.value = true;
        } else if (res.code === 1003) {
          messages.value.push({
            icon: icon_inform,
            title: '新订单通知',
            desc: res.msg,
            sendTime: dayjs().format('YYYY-MM-DD HH:mm')
          })
        }
      });
    }
  }
  return { messages, linkWebSocket };
})